using B.S.XZYData.Api.Wrter.Application.Command.Process;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Process
{
    /// <summary>
    /// 编辑工序处理器
    /// </summary>
    public class UpdateProcessHandler : IRequestHandler<UpdateProcessCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Domain.ZSHH.Process> processRepo;
        private readonly IBaseRepository<ProcessCollectionData> collectionDataRepo;
        private readonly ILogger<UpdateProcessHandler> logger;

        public UpdateProcessHandler(
            IBaseRepository<Domain.ZSHH.Process> processRepo,
            IBaseRepository<ProcessCollectionData> collectionDataRepo,
            ILogger<UpdateProcessHandler> logger)
        {
            this.processRepo = processRepo;
            this.collectionDataRepo = collectionDataRepo;
            this.logger = logger;
        }

        /// <summary>
        /// 编辑工序
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<int>> Handle(UpdateProcessCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            try
            {
                // 检查工序是否存在
                var existingProcess = await processRepo.GetValue(request.Id);
                if (existingProcess == null || existingProcess.IsDeleted)
                {
                    res.Msg = "工序不存在";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                // 验证工序名称唯一性（排除当前工序）
                var duplicateProcess = processRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.ProcessName == request.ProcessName && x.Id != request.Id)
                    .ToList()
                    .FirstOrDefault();

                if (duplicateProcess != null)
                {
                    res.Msg = "工序名称已存在";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    // 更新工序信息
                    existingProcess.ProcessName = request.ProcessName;
                    existingProcess.ReportingPermissions = request.ReportingPermissions;
                    existingProcess.ReportingRatio = request.ReportingRatio;
                    existingProcess.DefectiveItemList = request.DefectiveItemList;
                    existingProcess.TestField1 = request.TestField1;
                    existingProcess.TestField2 = request.TestField2;
                    existingProcess.Updator = request.Updator;
                    existingProcess.UpdatorDate = DateTime.Now;

                    var processResult = await processRepo.UpdateAsync(existingProcess);
                    if (processResult <= 0)
                    {
                        res.Msg = "更新工序失败";
                        res.Code = ApiEnum.Fail;
                        return await System.Threading.Tasks.Task.FromResult(res);
                    }

                    // 删除原有的工序采集数据
                    var existingCollectionData = collectionDataRepo.GetAll()
                        .Where(x => !x.IsDeleted && x.ProcessId == request.Id)
                        .ToList();

                    foreach (var item in existingCollectionData)
                    {
                        item.IsDeleted = true;
                        item.Updator = request.Updator;
                        item.UpdatorDate = DateTime.Now;
                        await collectionDataRepo.UpdateAsync(item);
                    }

                    // 新增新的工序采集数据（如果存在）
                    var collectionDataResult = 0;
                    if (request.CollectionDataList != null && request.CollectionDataList.Any())
                    {
                        var collectionDataEntities = request.CollectionDataList.Select(dto => new ProcessCollectionData
                        {
                            Id = YitIdHelper.NextId(),
                            ProcessId = request.Id,
                            DataType = dto.DataType,
                            DataName = dto.DataName,
                            Creator = request.Updator,
                            Updator = request.Updator
                        }).ToList();

                        collectionDataResult = await collectionDataRepo.CreateBatchAsync(collectionDataEntities);
                    }

                    transaction.Complete();

                    res.Data = processResult + collectionDataResult;
                    res.Msg = "更新工序成功";
                    res.Code = ApiEnum.Success;

                    logger.LogInformation($"更新工序成功，工序ID：{request.Id}，工序名称：{request.ProcessName}");
                }
                catch (Exception ex)
                {
                    logger.LogError($"更新工序事务异常：{ex.Message}");
                    res.Msg = "更新工序事务异常：" + ex.Message;
                    res.Code = ApiEnum.Error;
                }

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                logger.LogError($"更新工序异常：{ex.Message}");
                res.Msg = "更新工序异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 